package com.iandun.web.framework.core.configure.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * spring容器工具类
 *
 * @author :jason.liang
 * @date: 2021-05-19 20:04
 */
@Slf4j
@Component
@Lazy(false)
public class ApplicationContextHolder implements DisposableBean, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (applicationContext.getEnvironment().getActiveProfiles().length > 0) {
            log.debug("the application context env is : " +
                    applicationContext.getEnvironment().getActiveProfiles()[0]);
        }
        ApplicationContextHolder.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> entityClass) {
        return applicationContext.getBean(entityClass);
    }

    public static <T> T getBean(String name, Class<T> entityClass) {
        return applicationContext.getBean(name, entityClass);
    }

    @Override
    public void destroy() throws Exception {
        ApplicationContextHolder.applicationContext = null;
    }

    /**
     * 获取Request
     */
    public static HttpServletRequest getServletRequest() {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (Objects.nonNull(requestAttributes)) {
            return ((ServletRequestAttributes) requestAttributes).getRequest();
        }
        return null;
    }
}
